<?php
/*
 * @Author: ica caijianling@outlook.com
 * @Date: 2024-02-26 15:28:43
 * @LastEditors: ica caijianling@outlook.com
 * @LastEditTime: 2024-02-27 19:04:17
 * @FilePath: /api-itpno-app/app/Http/Middleware/PreventConcurrentRequests.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Cache\RateLimiter;
use Symfony\Component\HttpFoundation\Response;

class PreventConcurrentRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next)
    {
        $limiter = app(RateLimiter::class);

        if ($limiter->tooManyAttempts($this->resolveRequestSignature($request), 1)) {
            return response()->json(['message' => 'Too many requests. Please try again later.'], 429);
        }

        $limiter->hit($this->resolveRequestSignature($request), 1);

        $response = $next($request);

        $response->headers->add([
            'X-RateLimit-Limit' => 1,
            'X-RateLimit-Remaining' => $limiter->retriesLeft($this->resolveRequestSignature($request), 1),
        ]);

        return $response;
    }

    protected function resolveRequestSignature(Request $request)
    {
        return sha1($request->method() . '|' . $request->root() . '|' . $request->path() . '|' . $request->ip());
    }
}
